import { _decorator, Component, Node, AudioClip, AudioSource, CCBoolean, CCFloat, Enum, SphereCollider, ICollisionEvent, CCInteger } from 'cc';
import { Group } from '../Common/Constant';
const { ccclass, property } = _decorator;

enum AudioType {
    grig,
    owl
}

@ccclass('EnvirAudioManager')
export class EnvirAudioManager extends Component {
    @property(AudioClip)
    clips: AudioClip[] = [];

    @property({ type: CCBoolean })
    isLoop: boolean = false;

    @property({ type: CCBoolean })
    playOnAwake: boolean = false;

    @property({ type: Enum(AudioType) })
    clip: AudioType = AudioType.grig;

    @property({ type: CCFloat })
    checkRadius: number = 1;

    @property({ type: CCFloat, displayName: '音量', slide: true, max: 1, min: 0, step: 0.1 })
    volume: number = 1;

    @property({ type: CCInteger, displayName: '重新触发间隔s' })
    replayInterval: number = 3;

    audioSource: AudioSource = null!;
    collider: SphereCollider = null!;

    isPlayed: boolean = false;

    onLoad() {
        this.audioSource = this.getComponent(AudioSource);
        this.collider = this.getComponent(SphereCollider);

        this.collider.on('onTriggerEnter', this.onTriggerEnter, this);
        this.collider.on('onTriggerStay', this.onTriggerStay, this);
        this.collider.on('onTriggerExit', this.onTriggerExit, this);
    }

    onDestroy() {
        this.collider.off('onTriggerEnter', this.onTriggerEnter, this);
        this.collider.off('onTriggerStay', this.onTriggerStay, this);
        this.collider.off('onTriggerExit', this.onTriggerExit, this);
    }

    start() {
        this.collider.radius = this.checkRadius;

        if (this.playOnAwake) {
            this.Play();
        }
    }

    private onTriggerEnter(event: ICollisionEvent) {
        console.log(event.otherCollider.getGroup());

        if (event.otherCollider.getGroup() == Group.Player) {
            this.Play();
        }
    }

    private onTriggerStay(event: ICollisionEvent) {
    }

    private onTriggerExit(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == Group.Player) {
            this.scheduleOnce(() => {
                this.isPlayed = false;
            }, this.replayInterval);
        }
    }

    Play() {
        if (!this.isPlayed) {
            let clip = this.clips.find((clip) => clip.name == AudioType[this.clip]);

            if (clip) {
                this.audioSource.playOnAwake = this.playOnAwake;
                this.audioSource.loop = this.isLoop;
                this.audioSource.clip = clip;
                this.audioSource.volume = this.volume;
                this.audioSource.play();
            }

            this.isPlayed = true;
        }

    }

    Stop() {
        this.audioSource.stop();
    }

}


